<!--
 * @Description: 登录页面
 * @Author: wangfuwei
 * @Date: 2020-11-30 17:44:35
 * @LastEditors: wangfuwei
 * @LastEditTime: 2021-04-25 23:15:19
 * @FilePath: /horizon-frontend/src/views/user/Login.vue
-->
<template>
  <div class="main">
    <a-form class="user-layout-login" ref="loginForm" :model="form" :rules="rules" @submit="handleSubmit">
      <div style="height:39px;margin-bottom:12px;">
        <a-alert v-if="isLoginError" type="error" showIcon style="margin-bottom: 24px;" :message="$t('login.error')" closable :after-close="(isLoginError = false)" />
      </div>
      <a-form-item prop="username">
        <a-input size="large" type="text" :placeholder="$t('login.name_must')" v-model="form.username">
          <a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)' }" />
        </a-input>
      </a-form-item>
      <a-form-item prop="password">
        <a-input-password size="large" :placeholder="$t('login.pwd_must')" v-model="form.password">
          <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }" />
        </a-input-password>
      </a-form-item>
      <a-form-item>
        <a-checkbox v-model="rememberMe">{{ $t("login.remember") }}</a-checkbox>
      </a-form-item>
      <a-form-item style="margin-top:24px">
        <a-button size="large" type="primary" htmlType="submit" class="login-button" :loading="logining" :disabled="logining">{{ $t("login.title") }}</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script>
import md5 from "md5";
import { mapActions } from "vuex";

export default {
  data() {
    return {
      logining: false,
      isLoginError: false,
      rememberMe: false,
      form: {
        username: "",
        password: "",
      },
      rules: {
        username: [{ required: true, message: this.$t("login.name_must"), trigger: ["blur", "change"] }],
        password: [{ required: true, message: this.$t("login.pwd_must"), trigger: ["blur", "change"] }],
      },
    };
  },
  methods: {
    ...mapActions("user", ["login"]),
    handleSubmit(e) {
      e.preventDefault();
      let { login } = this;
      this.logining = true;
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          const loginParams = { ...this.form };
          loginParams.password = md5(loginParams.password);
          login(loginParams)
            .then(() => {
              this.$router.push({ path: "/" });
              this.isLoginError = false;
              this.logining = false;
            })
            .catch(() => {
              this.isLoginError = true;
              this.logining = false;
            });
        } else {
          this.logining = false;
          return false;
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.user-layout-login {
  label {
    font-size: 14px;
  }

  button.login-button {
    padding: 0 15px;
    font-size: 16px;
    height: 40px;
    width: 100%;
  }
}
</style>
